package com.intellagric.service.facility;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.intellagric.common.bean.LayuiDataGridResult;
import com.intellagric.common.bean.ResponseMessage;
import com.intellagric.common.utils.UUIDUtils;
import com.intellagric.dao.facility.FacilityUsedDao;
import com.intellagric.interfaces.facility.FacilityUsedService;
import com.intellagric.mapper.FacilityMapper;
import com.intellagric.mapper.FacilityUsedMapper;
import com.intellagric.mapper.SysUserMapper;
import com.intellagric.pojo.Facility;
import com.intellagric.pojo.FacilityExample;
import com.intellagric.pojo.FacilityUsed;
import com.intellagric.pojo.FacilityUsedExample;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

@Service
public class FacilityUsedServiceImpl implements FacilityUsedService {
    @Autowired
    private FacilityUsedMapper mapper;

    @Autowired
    private SysUserMapper userMapper;

    @Autowired
    private FacilityMapper facilityMapper;

    @Autowired
    private FacilityUsedMapper facilityUsedMapper;

    @Autowired
    private FacilityUsedDao dao;

    public ResponseMessage selectFacilityUsedById(String id) {
        ResponseMessage msg=new ResponseMessage();
        msg.add("usedBean",mapper.selectByPrimaryKey(id));
        return msg;
    }

    public ResponseMessage insertFacilityUsed(FacilityUsed FacilityUsed) {
////////////////////////////////////////
        FacilityUsed.setUsedBooked(false);
        FacilityUsed.setReturnback(false);

        int i=mapper.insertSelective(FacilityUsed);
        if (i!=0)
            return ResponseMessage.success();
        return ResponseMessage.fail();
    }

    public ResponseMessage deleteFacilityUsed(String id) {
        int i=mapper.deleteByPrimaryKey(id);
        if (i!=0)
            return ResponseMessage.success();
        return ResponseMessage.fail();
    }

    public ResponseMessage editFacilityUsed(FacilityUsed FacilityUsed) {
        Facility f=new Facility();
        f.setFacilityId(FacilityUsed.getFacilityId());
        f.setStatus(FacilityUsed.getAfterStatus());
        FacilityExample facilityExample=new FacilityExample();
        facilityExample.createCriteria().andFacilityIdEqualTo(FacilityUsed.getFacilityId());
        //改变facility的状态
        if(facilityMapper.updateByExampleSelective(f,facilityExample)!=0)
        {
            //归还时间
            Date date = new Date();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String actualUseTime = sdf.format(date);
            FacilityUsed.setActualUseTime(actualUseTime);

            FacilityUsedExample example=new FacilityUsedExample();
            example.createCriteria().andIdEqualTo(FacilityUsed.getId());


            int i =mapper.updateByExampleSelective(FacilityUsed,example);
            if (i!=0)
                return ResponseMessage.success();
        }

        return ResponseMessage.fail();
    }


    public LayuiDataGridResult getList(int page, int limit) {
        PageHelper.startPage(page,limit);
        FacilityUsedExample example=new FacilityUsedExample();
        example.createCriteria().andFacilityIdIsNotNull().andUsedBookedEqualTo(false).andReturnbackEqualTo(false);
        example.or().andFacilityIdIsNotNull().andUsedBookedEqualTo(true).andReturnbackEqualTo(true);
        List<FacilityUsed> list=mapper.selectByExample(example);
        PageInfo info=new PageInfo(list);
        return LayuiDataGridResult.success().add(list,info.getTotal());
    }
    public LayuiDataGridResult getListByCategoryId(int page,int limit,String categoryId){

        PageHelper.startPage(page,limit);
            FacilityUsedExample usedExample=new FacilityUsedExample();
        usedExample.createCriteria().andCategoryIdEqualTo(categoryId);
            List<FacilityUsed> results=mapper.selectByExample(usedExample);
        PageInfo info=new PageInfo(results);


        return LayuiDataGridResult.success().add(results,info.getTotal());
    }

    public LayuiDataGridResult batchDeleteFacilityUsed(String[] ids) {
        int i=dao.batchDeleteByPrimaryKey(ids);
        if (i!=0)
            return LayuiDataGridResult.success();
        return LayuiDataGridResult.fail();
    }

    /**
     * 根据商品名查询使用情况
     * @param page
     * @param limit
     * @param keyword
     * @return
     */
    public LayuiDataGridResult getFacilityUsedByKeyword(int page, int limit, String keyword) {
//        FacilityUsedExample facilityExample=new FacilityUsedExample();
//        facilityExample.createCriteria().andFacilityNameLike("%"+keyword+"%");
//        List<FacilityUsed> facilityList=facilityUsedMapper.selectByExample(facilityExample);
        PageHelper.startPage(page,limit);
        FacilityUsedExample facilityExample2=new FacilityUsedExample();
        facilityExample2.createCriteria().andFacilityIdLike("%"+keyword+"%");
        List<FacilityUsed> results=facilityUsedMapper.selectByExample(facilityExample2);
        PageInfo info=new PageInfo(results);
        return LayuiDataGridResult.success().add(results,info.getTotal());
    }



    /**
     *  预约列表
     * @param page
     * @param limit
     * @return
     */
    @Override
    public LayuiDataGridResult getBookedList(int page, int limit) {
        PageHelper.startPage(page,limit);
        FacilityUsedExample example=new FacilityUsedExample();
        List<FacilityUsed> list=mapper.selectByExample(example);
        PageInfo info=new PageInfo(list);
        return LayuiDataGridResult.success().add(list,info.getTotal());
    }

    /**
     * 根据分类获取预约列表
     * @param page
     * @param limit
     * @param categoryId
     * @return
     */
    @Override
    public LayuiDataGridResult getBookedListByCategoryId(int page, int limit, String categoryId) {
        FacilityExample example=new FacilityExample();
        example.createCriteria().andCategoryIdEqualTo(categoryId);
        List<Facility> list=facilityMapper.selectByExample(example);

        List<FacilityUsed> results=new ArrayList<FacilityUsed>();
        for (Facility pro:list){
            FacilityUsedExample usedExample=new FacilityUsedExample();
//            usedExample.createCriteria().andFacilityIdEqualTo(pro.getFacilityId()).andUsedBookedEqualTo(true).andReturnbackEqualTo(false);
            usedExample.createCriteria().andFacilityIdEqualTo(pro.getFacilityId());

            results.addAll(mapper.selectByExample(usedExample));
        }

        int toIndex=(page-1)*limit+limit;
        if(toIndex>results.size()){
            toIndex=results.size();
        }
        return LayuiDataGridResult.success().add(results.subList((page-1)*limit,toIndex),results.size());
    }


    /**
     * 添加预约记录
     * @param FacilityUsed
     * @return
     */
    public ResponseMessage insertFacilityBooked(FacilityUsed FacilityUsed) {
        ResponseMessage message=new ResponseMessage();
        //先查一下，预约的时间段是否已经有人预约了
        FacilityUsedExample example=new FacilityUsedExample();
        example.createCriteria().andUseDateBetween(FacilityUsed.getUseDate(),FacilityUsed.getReturnDate()).andReturnbackEqualTo(false).andFacilityIdEqualTo(FacilityUsed.getFacilityId());
        example.or().andReturnDateBetween(FacilityUsed.getUseDate(),FacilityUsed.getReturnDate()).andReturnbackEqualTo(false).andFacilityIdEqualTo(FacilityUsed.getFacilityId());
        example.or().andReturnDateGreaterThanOrEqualTo(FacilityUsed.getReturnDate()).andUseDateLessThanOrEqualTo(FacilityUsed.getUseDate()).andReturnbackEqualTo(false).andFacilityIdEqualTo(FacilityUsed.getFacilityId());
        List<FacilityUsed> list=mapper.selectByExample(example);
        if(list.size()==0||list==null) {
            FacilityUsed.setReturnback(false);
            FacilityUsed.setUsedBooked(true);

            if (mapper.insertSelective(FacilityUsed) != 0) {
                message.setCode(200);
            }else
                message.setCode(500);
        }else
            message.setCode(100);
        return message;
    }

    @Override
    public LayuiDataGridResult bookReturn(String facilityUsedId) {
        FacilityUsedExample example=new FacilityUsedExample();
        example.createCriteria().andIdEqualTo(facilityUsedId);

        Date date=new Date();
        SimpleDateFormat dr=new SimpleDateFormat("yyyy-MM-dd  HH:mm:ss");
        String actualUsedTime=dr.format(date);

        FacilityUsed used=new FacilityUsed();
        used.setActualUseTime(actualUsedTime);

        if(mapper.updateByExampleSelective(used,example)!=0){
         return LayuiDataGridResult.success();
        }
        return LayuiDataGridResult.fail();
    }
    @Override
    public LayuiDataGridResult batchBookReturn(String[] facilityUsedIds) {
        int i=0;
        for (String facilityUsedId: facilityUsedIds) {
            FacilityUsedExample example = new FacilityUsedExample();
            example.createCriteria().andIdEqualTo(facilityUsedId);
            FacilityUsed used = new FacilityUsed();
            used.setReturnback(true);
            i+=mapper.updateByExampleSelective(used,example);
        }
        if(i==facilityUsedIds.length){
            return LayuiDataGridResult.success();
        }
        return LayuiDataGridResult.fail();
    }

    @Override
    public String[] getRecentDate() {
        Calendar calendar=Calendar.getInstance();
        //calendar.set(calendar.get(Calendar.YEAR),calendar.get(Calendar.MONTH),calendar.get(Calendar.DAY_OF_MONTH));
        String[] strs=new String[7];
        for (int i =6;i>=0;i--) {
            calendar.add(Calendar.DAY_OF_MONTH, -1);
            strs[i]=calendar.get(calendar.MONTH)+1+"月"+calendar.get(Calendar.DAY_OF_MONTH)+"日";
        }

        return strs;
    }

    @Override
    public long[] getRecentData() throws ParseException {
        SimpleDateFormat format=new SimpleDateFormat("yyyy-MM-dd");

        Calendar calendar=Calendar.getInstance();
        long[] ints=new long[7];
        for (int i =6;i>=0;i--) {
            String tomorrow=calendar.get(Calendar.YEAR)+"-"+(calendar.get(Calendar.MONTH)+1)+"-"+calendar.get(Calendar.DAY_OF_MONTH);
            calendar.add(Calendar.DAY_OF_MONTH, -1);
            String today=calendar.get(Calendar.YEAR)+"-"+(calendar.get(Calendar.MONTH)+1)+"-"+calendar.get(Calendar.DAY_OF_MONTH);
            Date date=format.parse(today);
            FacilityUsedExample example=new FacilityUsedExample();
            example.createCriteria().andUseDateBetween(date,format.parse(tomorrow));
            ints[i]=mapper.countByExample(example);
        }


        return ints;
    }
}
